package com.lagou.demo.controller;

import com.lagou.demo.service.IDemoService;
import com.lagou.edu.mvcframework.annotations.LagouAutowired;
import com.lagou.edu.mvcframework.annotations.LagouController;
import com.lagou.edu.mvcframework.annotations.LagouRequestMapping;
import com.lagou.edu.mvcframework.annotations.Security;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@LagouController
@LagouRequestMapping("/demo")
@Security({"role_001", "role_002"})
public class DemoController {

    @LagouAutowired
    private IDemoService demoService;

    /**
     * url: http://localhost:8080/demo/handle01?username=Jerry
     * url: http://localhost:8080/demo/handle02?username=Jerry
     *
     * 1.@Security可是放在类或者方法上，放在方法上，这个接口需要权限校验，放在类上，整个controller的接口都需要权限校验
     * 2.为了方便验证功能,在init()方法中初始化一个List，存储user对象，包含权限字符，模拟内存中的权限，LgDispatcherServlet.initUser()
     *      用户 :   权限
     *      Jack:   role_001
     *      Rose:   role_002
     *      Tom:    role_001 role_002
     *      Jerry:  role_001 role_002 role_003
     * 3.在进行参数绑定之前进行权限校验，节省性能，LgDispatcherServlet.permissionValidation()方法
     * 4.权限统一抛出SecurityException异常，统一捕获，response显示error message
     * 5.首先校验参数username是否存在内存中，存在查询关联的权限进行匹配，不存在抛出异常输出
     * 6.校验_方法级_的@Security注解，校验_类级_@Security注解
     *      1)如果都有注解，则需要同时满足
     *      2)只有其中一个，只校验一个
     *      3)都没有，则不校验
     *
     * @param username
     * @return
     */
    @Security("role_003")
    @LagouRequestMapping("/handle01")
    public String security01(HttpServletRequest request, HttpServletResponse response,
            String username) throws IOException {
        System.out.println("Security: " + username);
        response.getWriter().write(
                "<html>\n" + "<body>\n" + "<h2>Login success: Hello " + username + "</h2>\n" + "</body>\n"
                        + "</html>");
        return username;
    }

    @Security("role_004")
    @LagouRequestMapping("/handle02")
    public String security02(HttpServletRequest request, HttpServletResponse response,
            String username) throws IOException {
        System.out.println("Security: " + username);
        response.getWriter().write(
                "<html>\n" + "<body>\n" + "<h2>Login success: Hello " + username + "</h2>\n" + "</body>\n"
                        + "</html>");
        return username;
    }

    /**
     * URL: /demo/query?name=lisi
     * @param request
     * @param response
     * @param name
     * @return
     */
    @LagouRequestMapping("/query")
    public String query(HttpServletRequest request, HttpServletResponse response,String name) {
        return demoService.get(name);
    }
}
